package com.mygame.game_server.async;

import com.mygame.game_server.MainMgsProcessor;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class AsyncOperationProcessor {

    private final static AsyncOperationProcessor _instance = new AsyncOperationProcessor();

    /**
     * 单线程数组
     */
    private final ExecutorService[] _esArray = new ExecutorService[8];

    /**
     * 私有化
     */
    private AsyncOperationProcessor() {
//        _esArray[0].shutdown();
        for (int i = 0; i < _esArray.length; i++) {
            final String threadName = "AsyncOperationProcessor["+ i +"]";
            _esArray[i] = Executors.newSingleThreadExecutor((r)->{
                Thread t = new Thread(r);
                t.setName(threadName);
                return t;
            });
        }

    }

//    /**
//     *  创建一个单线程的线程池 装饰器模式
//     */
//    private   final ExecutorService _es = Executors.newFixedThreadPool(8,(newRunnable) ->{
//        Thread newThread = new Thread(newRunnable);
//        newThread.setName("AsyncOperationProcessor");
//        return newThread;
//    });




    /**
     * 获取单例
     * @return AsyncOperationProcessor
     */
    public static AsyncOperationProcessor getInstance() {
        return _instance;
    }

    /**
     * 调用过程
     * @param op 异步操作
     */
    public  void process(IAsyncOperation op){
        if (null == op) {
            return;
        }
        int bindId = Math.abs(op.getBindId());
        int esIndex = bindId & _esArray.length - 1;
        _esArray[esIndex].submit(()->{
            // 执行异步操作
            op.doAsync();
            // 回到主线程执行完成逻辑
            MainMgsProcessor.getInstance().process(op::doFinish);
        });

    }


}
